<template>
  <div>
    <header class="game_modal_header">收费明细</header>

    <div v-loading="loading" class="logistics_list">
      <!-- 酒店费用 -->
      <div v-if="hotelData.hotelEntrys && hotelData.hotelEntrys.length > 0" class="gl_mb_10 gameEntry_shadow">
        <el-row class="gl_py_5" type="flex" justify="space-between">
          <el-col :span="20">
            <span class="charge_item_title gl_mr_20">酒店费用</span>
          </el-col>
        </el-row>
        <el-table class="table gl_table_noBorder" :data="hotelData.hotelEntrys" size="mini">
          <el-table-column type="index" label="序号" :width="50" align="center" />
          <el-table-column prop="hotelName" label="酒店名称" />
          <el-table-column prop="roomName" label="房型名称" />
          <el-table-column prop="reserveNumber" label="预定间数" :width="80" align="center">
            <template slot-scope="{ row }">
              <span>{{ row.reserveNumber }}间</span>
            </template>
          </el-table-column>
          <el-table-column label="入住时间" :width="90" align="center">
            <template slot-scope="{ row }">
              <span>{{ row.checkInDate | FormatDate('yyyy-MM-dd') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="离店时间" :width="90" align="center">
            <template slot-scope="{ row }">
              <span>{{ row.checkOutDate | FormatDate('yyyy-MM-dd') }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="dayNum" label="天数" :width="80" align="center">
            <template slot-scope="{ row }">
              <span>共{{ row.dayNum }}晚</span>
            </template>
          </el-table-column>
          <el-table-column prop="receptionName" label="预定人姓名" />
          <el-table-column prop="receptionPhoneNumber" label="预订人手机号" :width="100" />
          <el-table-column prop="extraBedNumber" label="加床数量" :width="70" align="center">
            <template slot-scope="{ row }">
              <span>{{ row.extraBedNumber || '- -' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="amount" label="价格">
            <template slot-scope="{ row }">
              <span>￥{{ formatMoney(row.amount) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" :width="100">
            <template slot-scope="{ row }">
              <p>{{ row.remark || '- -' }}</p>
            </template>
          </el-table-column>
        </el-table>
        <el-row class="gl_py_5 gl_fs_14 gl_ft_weight" type="flex" justify="end">
          <el-col :span="4" align="right">
            <span>共计 {{ hotelData.count }} 项</span>
          </el-col>
          <el-col :span="4" align="right">
            <span>合计：<span class="gl_color_error">{{ formatMoney(hotelData.amount) }}</span> 元</span>
          </el-col>
        </el-row>
      </div>
      <!-- 接待费用 -->
      <div v-if="receptionData.receptionEntrys && receptionData.receptionEntrys.length > 0" class="gl_mb_10 gameEntry_shadow">
        <el-row class="gl_py_5" type="flex" justify="space-between">
          <el-col :span="20">
            <span class="charge_item_title gl_mr_20">接待费用</span>
          </el-col>
        </el-row>
        <el-table class="table gl_table_noBorder" :data="receptionData.receptionEntrys" size="mini">
          <el-table-column type="index" label="序号" :width="50" align="center" />
          <el-table-column label="接送地点" :min-width="160">
            <template slot-scope="{ row }">
              <span>{{ row.departureStation }}</span>
              <span> -- </span>
              <span>{{ row.arrivalStation }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="carType" label="车辆类型" />
          <el-table-column prop="carSeatCode" label="座位数">
            <template slot-scope="{ row }">
              <span v-if="row.carSeatCode">
                <template v-for="ktem in dict.carSeatType">
                  {{ ktem.code === row.carSeatCode ? ktem.value: '' }}
                </template>
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="carColor" label="颜色" :width="70" align="center" />
          <el-table-column prop="trainNumber" label="车次">
            <template slot-scope="{ row }">
              <span>{{ row.trainNumber || '- -' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="receptionName" label="预定人姓名" />
          <el-table-column prop="receptionPhoneNumber" label="预定人手机号" :width="100" />
          <el-table-column prop="pickUpCarTime" label="接车时间" :width="140" align="center">
            <template slot-scope="{ row }">
              <span v-if="row.pickUpCarTime == '0001-01-01T00:00:00' || row.pickUpCarTime == null">- -</span>
              <span v-else>{{ row.pickUpCarTime | FormatDate('yyyy-MM-dd HH:mm:ss') }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="pickUpCarNumber" label="接车车辆数量" :width="100" align="center">
            <template slot-scope="{ row }">
              <span>{{ row.pickUpCarNumber || '- -' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="deliverCarTime" label="送车时间" :width="140" align="center">
            <template slot-scope="{ row }">
              <span v-if="row.deliverCarTime == '0001-01-01T00:00:00' || row.deliverCarTime == null">- -</span>
              <span v-else>{{ row.deliverCarTime | FormatDate('yyyy-MM-dd HH:mm:ss') }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="deliverCarNumber" label="送车车辆数量" :width="100" align="center">
            <template slot-scope="{ row }">
              <span>{{ row.deliverCarNumber || '- -' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="amount" label="价格">
            <template slot-scope="{ row }">
              <span>￥{{ formatMoney(row.amount) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" :width="100">
            <template slot-scope="{ row }">
              <p>{{ row.remark || '- -' }}</p>
            </template>
          </el-table-column>
        </el-table>
        <el-row class="gl_py_5 gl_fs_14 gl_ft_weight" type="flex" justify="end">
          <el-col :span="4" align="right">
            <span>共计 {{ receptionData.count }} 项</span>
          </el-col>
          <el-col :span="4" align="right">
            <span>合计：<span class="gl_color_error">{{ formatMoney(receptionData.amount) }}</span> 元</span>
          </el-col>
        </el-row>
      </div>
      <!-- 餐饮费用 -->
      <div v-if="cateringData.cateringEntrys && cateringData.cateringEntrys.length > 0" class="gl_mb_10 gameEntry_shadow">
        <el-row class="gl_py_5" type="flex" justify="space-between">
          <el-col :span="20">
            <span class="charge_item_title gl_mr_20">餐饮费用</span>
          </el-col>
        </el-row>
        <el-table class="table gl_table_noBorder" :data="cateringData.cateringEntrys" size="mini">
          <el-table-column type="index" label="序号" :width="50" align="center" />
          <el-table-column prop="restaurantName" label="饭店名称" />
          <el-table-column prop="foodName" label="食品名称" />
          <el-table-column prop="foodTypeName" label="餐别" :width="70" align="center" />
          <el-table-column label="配送时间" :width="120" align="center">
            <template slot-scope="{ row }">
              <p>{{ 10 > row.deliveryStartHour ? '0' + row.deliveryStartHour : row.deliveryStartHour }}:{{ 10 > row.deliveryStartMinute ? '0' + row.deliveryStartMinute : row.deliveryStartMinute }} - {{ 10> row.deliveryEndHour ? '0' + row.deliveryEndHour : row.deliveryEndHour }}:{{ 10 > row.deliveryEndMinute ? '0' + row.deliveryEndMinute : row.deliveryEndMinute }}</p>
            </template>
          </el-table-column>
          <el-table-column prop="deliveryAddress" label="配送地址" :width="160" />
          <el-table-column prop="receptionName" label="预定人姓名" :min-width="120" />
          <el-table-column prop="receptionPhoneNumber" label="预订人手机号" :width="100" />
          <el-table-column prop="reserveNumber" label="预订份数" :width="70" align="center" />
          <el-table-column prop="time" label="开始/结束订餐日期" :width="160">
            <template slot-scope="{ row }">
              <span>{{ row.reserveStartDate | FormatDate('yyyy-MM-dd') }}至{{ row.reserveEndDate | FormatDate('yyyy-MM-dd') }}</span>
              <span> 共{{ row.dayNum }}天</span>
            </template>
          </el-table-column>
          <el-table-column prop="amount" label="价格">
            <template slot-scope="{ row }">
              <span>￥{{ (row.amount / 100).toFixed(2) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" :width="100">
            <template slot-scope="{ row }">
              <p>{{ row.remark || '- -' }}</p>
            </template>
          </el-table-column>
        </el-table>
        <el-row class="gl_py_5 gl_fs_14 gl_ft_weight" type="flex" justify="end">
          <el-col :span="4" align="right">
            <span>共计 {{ cateringData.count }} 项</span>
          </el-col>
          <el-col :span="4" align="right">
            <span>合计：<span class="gl_color_error">{{ formatMoney(cateringData.amount) }}</span> 元</span>
          </el-col>
        </el-row>
      </div>
      <!-- 总计 -->
      <el-row v-if="hotelData.hotelEntrys || receptionData.receptionEntrys || cateringData.cateringEntrys" class="summary_wrap">
        <el-col :span="6">
          <p v-if="hotelData.amount && hotelData.hotelEntrys && hotelData.hotelEntrys.length > 0" class="gl_fs_16 gl_ft_weight gl_mt_15">
            <span class="gl_pr_20">酒店费用</span>
            <span>{{ formatMoney(hotelData.amount) }} 元</span>
          </p>
          <p v-if="receptionData.amount && receptionData.receptionEntrys && receptionData.receptionEntrys.length > 0" class="gl_fs_16 gl_ft_weight gl_mt_15">
            <span class="gl_pr_20">接待费用</span>
            <span>{{ formatMoney(receptionData.amount) }} 元</span>
          </p>
          <p v-if="cateringData.amount && cateringData.cateringEntrys && cateringData.cateringEntrys.length > 0" class="gl_fs_16 gl_ft_weight gl_mt_15">
            <span class="gl_pr_20">餐饮费用</span>
            <span>{{ formatMoney(cateringData.amount) }} 元</span>
          </p>
        </el-col>
        <el-col :span="8">
          <p class="gl_fs_16 gl_ft_weight gl_mt_15">
            <span class="gl_pr_20">合计</span>
            <span class="gl_color_error">{{ formatMoney(amount) }}</span>
            <span> 元</span>
          </p>
        </el-col>
      </el-row>
      <div v-if="!hotelData.hotelEntrys && !receptionData.receptionEntrys && !cateringData.cateringEntrys" v-loading="calcEntryLoading" class="no_entry">
        暂无收费明细，请先预定！
        <!-- <el-button type="text" @click="reGetLogisticOrder">点击重试</el-button> -->
      </div>
    </div>

    <!-- 底部功能按钮 -->
    <el-row class="control_row gl_mb_20">
      <el-col :span="24" align="center">
        <el-button type="primary" plain class="prev" size="small" style="border-radius: 8px;" @click="toPrev()">上一步</el-button>
        <el-button :loading="payLoading" :disabled="!hotelData.hotelEntrys && !receptionData.receptionEntrys && !cateringData.cateringEntrys" type="info" :class="[ hotelData.hotelEntrys || receptionData.receptionEntrys || cateringData.cateringEntrys ? 'pay_btn': 'no_pay_btn' ]" size="small" @click="clickPay()">去支付</el-button>
      </el-col>
    </el-row>
    <!-- 选择支付方式弹框 -->
    <el-dialog class="gl_dialog_TitleLine" title="选择支付方式" :visible.sync="dialogVisibleForPay" :close-on-click-modal="false" width="650px">
      <div v-loading="modalPayLoding" class="pay_type_list">
        <div class="pay_type_item pay_type_offline gl_clear" @click="clickPayOffline()">线下支付</div>
        <div class="pay_type_item pay_type_online gl_clear" @click="clickPayOnline()">线上支付</div>
      </div>
    </el-dialog>

    <form id="form" ref="form" action="https://unipay.ydfuture.com/api/v1/trade/cashDesk" method="post" style="display:none">
      <input ref="pay_params" type="text" name="pay_params" value="">
      <button type="submit">提交</button>
    </form>

    <el-dialog
      class="gl_dialog_TitleLine"
      title="线下收款账户信息"
      width="640px"
      :visible.sync="offlineDialogVisible"
      :show-close="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <offline-pay-info :offline-data="offlineData" />
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" type="primary" @click="jumpToOrderCenter">前往订单中心</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import OfflinePayInfo from '@/components/OfflinePayInfo';
import { mapState, mapActions } from 'vuex';
import {
  api_GET_EventsManagementHotelEntryHotelEntryLogisticEntryId, // 获取预定中的酒店数据
  api_GET_EventsManagementReceptionEntryReceptionEntryLogisticEntryId, // 获取预定中的接待数据
  api_GET_EventsManagementCateringEntryCateringEntryLogisticEntryId, // 获取预定中的就餐数据
  api_GET_EventsManagementLogisticEntryLogisticPayInfo, // 获取设置的支付信息
  api_POST_EventsManagementLogisticEntrySubmitOrderLogisticEntryId // 提交订单
} from '@/extend/api/gameswaggerApi/app';
import {
  api_GET_TrainTrainningLogisticEntryLogisticPayInfo, // 获取设置的支付信息
  api_POST_TrainTrainningLogisticEntrySubmitOrderLogisticEntryId // 提交订单
} from '@/extend/api/trainswaggerApi/app';
import {
  // api_GET_TradeOrderDetails, // 根据订单号获取订单详情
  api_GET_TradePersonalOrderCollectionCode, // 获取线下支付订单的收款码信息
  api_GET_TradePayOrderParameter // 获取支付订单的参数
} from '@/extend/api/swaggerApi/app';
import {
  Api_GET_TradePayOrderParameterQO
} from '@/lib/form/swaggerForm';

export default {
  components: {
    OfflinePayInfo
  },
  props: {
    form: {
      type: Object,
      default() {
        return {};
      }
    },
    isShow: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      loading: false,
      payLoading: false,
      hotelData: {}, // 酒店
      receptionData: {}, // 接待
      cateringData: {}, // 餐饮
      logisticPayInfo: {}, // 支付方式
      isTrain: false, // 是否是培训
      offlineDialogVisible: false,
      dialogVisibleForPay: false, // 选择支付方式弹窗
      isOnlinePayment: true, // 是否是线上支付
      modalPayLoding: false,
      currentUser: {},
      orderNo: '', // 订单编号
      calcEntryLoading: false,
      orderParameterQO: new Api_GET_TradePayOrderParameterQO(),
      offlineData: {}
    };
  },
  computed: {
    ...mapState({
      UserType: state => state.user.currentUserType,
      dict: state => state.dict.dict
    }),
    amount() {
      const h = this.hotelData.amount || 0;
      const r = this.receptionData.amount || 0;
      const c = this.cateringData.amount || 0;
      return h + r + c;
    }
  },
  watch: {
    isShow: {
      immediate: true,
      handler(val) {
        if (val) {
          if (this.$route.name.indexOf('Train') > -1) {
            this.isTrain = true; // 是培训
          }
          this.hasPayWayInLogistic();
          this.getHotelData();
          this.getReceptionData();
          this.getCateringData();
        }
      }
    },
    'UserType': {
      immediate: true,
      deep: true,
      handler(val) {
        // 获取当前用户角色
        if (val) {
          this.currentUser.registerId = val.registerId;
          this.currentUser.delegationId = val.delegationId;
        }
      }
    }
  },
  created() {
    if (this.$route.name.indexOf('Train') > -1) {
      this.isTrain = true; // 是培训
    }
    this.getDict();
  },
  methods: {
    ...mapActions({ getDict: 'dict/getDict' }),
    // 上一步
    toPrev() {
      this.$emit('toPrev');
    },
    reGetLogisticOrder() {
      this.getHotelData();
      this.getReceptionData();
      this.getCateringData();
    },
    // 酒店
    getHotelData() {
      var that = this;
      that.loading = true;
      api_GET_EventsManagementHotelEntryHotelEntryLogisticEntryId(this.form.id).then(res => {
        that.hotelData = res || {};
        that.loading = false;
      }, (error) => {
        that.loading = false;
        that.$message({ type: 'error', message: error.error.message });
      });
    },
    // 接待
    getReceptionData() {
      var that = this;
      that.loading = true;
      api_GET_EventsManagementReceptionEntryReceptionEntryLogisticEntryId(this.form.id).then(res => {
        that.receptionData = res || {};
        that.loading = false;
      }, (error) => {
        that.loading = false;
        that.$message({ type: 'error', message: error.error.message });
      });
    },
    // 餐饮
    getCateringData() {
      var that = this;
      that.loading = true;
      api_GET_EventsManagementCateringEntryCateringEntryLogisticEntryId(this.form.id).then(res => {
        that.cateringData = res || {};
        that.loading = false;
      }, (error) => {
        that.loading = false;
        that.$message({ type: 'error', message: error.error.message });
      });
    },
    hasPayWayInLogistic () {
      var that = this;
      const providerName = this.isTrain ? 'T' : 'C';
      const form = {
        providerName: providerName,
        providerKey: this.$route.query.id
      };
      if (this.isTrain) {
        // 培训
        api_GET_TrainTrainningLogisticEntryLogisticPayInfo(form).then(res => {
          that.logisticPayInfo = res || {};
        }, (error) => {
          that.$message({ type: 'error', message: error.error.message });
        });
      } else {
        // 赛事
        api_GET_EventsManagementLogisticEntryLogisticPayInfo(form).then(res => {
          that.logisticPayInfo = res || {};
        }, (error) => {
          that.$message({ type: 'error', message: error.error.message });
        });
      }
    },
    // 点击支付按钮
    clickPay () {
      this.payLoading = true;
      // 请注意代码顺序不可调整
      const _setOnline = this.logisticPayInfo.isOpenOnlinePay; // 设置了线上支付
      const _setOffline = this.logisticPayInfo.isOpenOfflinePay; // 设置了线下支付
      // 当同时设置了线上与线下支付时，弹窗让用户选择支付方式
      if (_setOnline && _setOffline) {
        this.dialogVisibleForPay = true;
        this.payLoading = false;
        return;
      }
      // 仅设置了线上支付
      if (_setOnline) {
        this.clickPayOnline();
        return;
      }
      // 仅设置了线下支付
      if (_setOffline) {
        this.clickPayOffline();
        return;
      }
    },
    // 线上支付
    clickPayOnline () {
      this.isOnlinePayment = true; // 是否是线上订单
      this.submitOrder();
    },
    // 线下支付
    clickPayOffline () {
      this.isOnlinePayment = false; // 是否是线上订单
      this.submitOrder();
    },
    // 提交订单
    submitOrder() {
      var that = this;
      that.modalPayLoding = true;
      const _vo = {
        registerId: that.currentUser.registerId,
        isOnlinePayment: that.isOnlinePayment
      };
      if (this.isTrain) {
        // 培训后勤订单
        api_POST_TrainTrainningLogisticEntrySubmitOrderLogisticEntryId(that.form.id, _vo).then(res => {
          that.orderNo = res.orderNo;
          if (that.isOnlinePayment) {
          // 如果是线上支付
            that.payment(res.orderNo);
          } else {
          // 线下支付，展示获取订单信息，展示收款账户信息
            that.getOrderDetails(res.orderNo);
          }
          that.modalPayLoding = false;
          that.payLoading = false;
        }).catch(error => {
          that.$message({ type: 'error', message: `订单创建失败！${error.error.message}` });
          that.modalPayLoding = false;
          that.payLoading = false;
        });
      } else {
        // 赛事后勤订单
        api_POST_EventsManagementLogisticEntrySubmitOrderLogisticEntryId(that.form.id, _vo).then(res => {
          that.orderNo = res.orderNo;
          if (that.isOnlinePayment) {
          // 如果是线上支付
            that.payment(res.orderNo);
          } else {
          // 线下支付，展示获取订单信息，展示收款账户信息
            that.getOrderDetails(res.orderNo);
          }
          that.modalPayLoding = false;
          that.payLoading = false;
        }).catch(error => {
          that.$message({ type: 'error', message: `订单创建失败！${error.error.message}` });
          that.modalPayLoding = false;
          that.payLoading = false;
        });
      }
    },
    // 获取订单详情，用于线下支付展示收款账户信息
    getOrderDetails (orderNo) {
      api_GET_TradePersonalOrderCollectionCode({ orderNo: orderNo }).then(res => {
        res._orderNo = orderNo;
        this.offlineData = res;
        this.offlineDialogVisible = true;
      }).catch(error => {
        this.$message({ type: 'error', message: `订单详情获取失败！${error.error.message}` });
      });
    },
    // 去支付
    payment(orderNo) {
      if (orderNo) {
        const _origin = window.location.origin;
        const _pathname = window.location.pathname;
        const _orderUrl = '#/myCenter/order/main';
        const url = _origin + _pathname + _orderUrl;
        this.orderParameterQO.OrderNo = orderNo;
        this.orderParameterQO.ReturnUrl = url; // 支付成功后跳转的地址
        api_GET_TradePayOrderParameter(this.orderParameterQO)
          .then(res => {
            this.$refs.pay_params.value = res.parameter.replace(/\s*/g, '');
            this.$refs.form.submit();
          });
      }
    },
    // 跳转到订单中心
    jumpToOrderCenter () {
      if (this.isTrain) {
        const url = window.location.origin + '/game.html#/myCenter/order/main?out_trade_no=' + this.orderNo;
        window.location.href = url;
        // 线下支付,直接去订单中心
      } else {
        // 线下支付,直接去订单中心
        this.$router.push({
          path: '/myCenter/order/main?out_trade_no=' + this.orderNo
        });
      }
    },
    // 格式化货币格式 （分）
    formatMoney(num) {
      if (typeof num === 'number' && !Number.isNaN(num)) {
        // num 是数字类型 且不是 NaN
        let strNum = String(num); // 金额文本类型
        if (num >= 0) {
          strNum = strNum.padStart(3, '0'); // 用0填充保证最小三位数
          return strNum.slice(0, -2) + '.' + strNum.slice(-2); // 金额拼接
        } else {
          const _mark = strNum.slice(0, 1); // 负号
          const _noMark = strNum.slice(1); // 无负号数值
          strNum = _noMark.padStart(3, '0'); // 用0填充保证最小三位数
          return _mark + strNum.slice(0, -2) + '.' + strNum.slice(-2); // 金额拼接
        }
      } else {
        return '';
      }
    }
  }
};
</script>

<style>
.logistics_list .el-table,
.logistics_list .el-table__body-wrapper {
  min-height: auto;
  border-radius: 4px;
}
</style>

<style lang="scss" scoped>
.logistics_list {
  padding: 0 40px;
}
.gameEntry_shadow {
  padding: 12px;
  border-radius: 8px;
  background-color: #fff;
  box-shadow: 0px 10px 36px 0px rgba(0,0,0,0.08);
}
.charge_item_title {
  font-size: 16px;
  line-height: 24px;
  font-weight: bold;
  margin-left: 22px;
}
.summary_wrap {
  padding: 5px 0 39px 34px;
  border-radius: 8px;
  background-color: #fff;
  box-shadow: 0px 10px 36px 0px rgba(0,0,0,0.08);
}
.control_row {
  margin-top: 24px;
}

.pay_type_list {
  display: flex;
  justify-content: space-around;
}
.pay_type_item {
  width: 260px;
  height: 84px;
  padding: 0 50px;
  text-align: right;
  color: #fff;
  font-size: 24px;
  line-height: 84px;
  cursor: pointer;
}
.pay_type_online {
  background-image: url('../../../../assets/images/pay/online.png');
  background-repeat: no-repeat;
}
.pay_type_offline {
  background-image: url('../../../../assets/images/pay/offline.png');
  background-repeat: no-repeat;
}
.pay_btn {
  border-radius: 8px;
  background: #ff704a;
  border-color: #ff704a;
}
.no_pay_btn {
  border-radius: 8px;
}
.no_entry {
  position: relative;
  color: #909399;
  font-size: 14px;
  padding: 60px 0;
  text-align: center;
}
</style>
